package com.lcifn.springmvc.config;

import java.util.List;
import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.XmlViewResolver;

import com.lcifn.springmvc.controller.AdviceController;
import com.lcifn.springmvc.interceptor.ExampleInteceptor;

@Configuration
//@EnableWebMvc
@ComponentScan(basePackages="com.lcifn.springmvc.controller")
public class AppServletConfig extends WebMvcConfigurationSupport{

	@Override
	public RequestMappingHandlerMapping requestMappingHandlerMapping() {
		final RequestMappingHandlerMapping requestMappingHandlerMapping = super.requestMappingHandlerMapping();
		// URL映射查询包括所有父类上下文
		// 不生效，原因是initHandlerMethod是在初始化方法afterPropertiesSet中完成的，此时设置已晚
		// 对于springmvc，默认约定Controller就应该由servlet上下文进行加载
		requestMappingHandlerMapping.setDetectHandlerMethodsInAncestorContexts(true);
		// 支持matrix矩阵表达式
		requestMappingHandlerMapping.setRemoveSemicolonContent(false);
		return requestMappingHandlerMapping;
	}
	
	@Override
	protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
		super.configureHandlerExceptionResolvers(exceptionResolvers);
		
		Properties mappings = new Properties();
		mappings.setProperty("com.lcifn.springmvc.exception.BusinessException", "businessEx");
		
		SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
		resolver.setDefaultErrorView("error");
		resolver.setExceptionMappings(mappings);
		//exceptionResolvers.add(resolver);
	}
	
	@Override
	protected void configureViewResolvers(ViewResolverRegistry registry) {
		super.configureViewResolvers(registry);
		registry.viewResolver(new InternalResourceViewResolver("/WEB-INF/", ".jsp"));
	}
	
	@Override
	protected void addInterceptors(InterceptorRegistry registry) {
		super.addInterceptors(registry);
		registry.addInterceptor(new ExampleInteceptor());
	}
	
}
